 /* ********************************************************************************
  *    Copyright:  (C) 2023 LN
  *    All rights reserved.
  *
  *      Filename: 	 client.c
  *    Description:  This file 
  *                 
  *      Version:  1.0.0(2023年04月05日)
  *       Author:  Li Haipeng <NULL>
  *    ChangeLog:  1, Release initial version on "2023年04月05日 23时38分38秒"
  *                    
  *
  ********************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <signal.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <getopt.h>
#include <unistd.h>
#include "logger.h"
#include "pack_data.h"
#include <mosquitto.h>
#include <netdb.h>


void print_usage(char *progname)
{
    printf("%s usage:\n",progname);
    printf("example:./a.out -p 1 \n");
    printf("-H(--host):sepcify host name\n");
    printf("-p(--pattern):cloud platfrom[alyun:1 、tenxuyun:2 、 huaweiyun:3]\n");
    printf("-i(--interval):acquisition time\n");
    printf("-h(--help):print this help infomation.\n");
    return ;
}

int main(int argc,char **argv)
{
	struct mosquitto    	*mosq = NULL;
	bool                	 session = true ;
    int                      get_data_flag = 0;
    int                      interval = 3;
    int                      ch;
    int                      option = 1;
    int                      port=1883;
	char					 msg[1024];
    int                      rv = 0;
    char                     log[16] = "logger.log";
    char                    *ini_path = "./aliyun.ini";
	time_t					 cur_time;
	time_t					 now_time;
	data_mqtt				 mqtt;

    struct option            opts[] = {
                                        {"Host", no_argument, NULL,'H'},
                                        {"pattern", no_argument, NULL,'p'},
                                        {"interval", no_argument, NULL,'i'},
                                        {"help", no_argument, NULL,'h'},
                                        {NULL,0,NULL,0},
                                      };


    while((ch = getopt_long(argc , argv ,"H:p:i:d:h" , opts , NULL)) != -1)
    {
        switch(ch)
        {
            case 'p':
                option = atoi(optarg);
                break;
            case 'i':
                interval = atoi(optarg);
                break;
            case 'h':
                print_usage(argv[0]);
                return 0;
        }
    }

    if(logger_init(NULL, 5) < 0)
    {
        fprintf(stderr,"initial logger system failure\n");
		return 0;
    }

   /* if( !open_db(pack.devsn) )
	{
		log_error("Open data failure!");
		return 0;
	}*/
	get_mqttdata(ini_path,&mqtt,option);

	rv = mosquitto_lib_init();
	if( rv != MOSQ_ERR_SUCCESS )
	{
		log_error("Mosq_Connect() failed: %s", strerror(errno) );
		mosquitto_lib_cleanup() ;	
		return 0;
	}

	mosq = mosquitto_new(mqtt.clientid, session, NULL) ;
	if(!mosq)
	{
		log_error("new pub_test failure:%s",strerror(errno));
		mosquitto_destroy(mosq);
		mosquitto_lib_cleanup();
		return 0;
	}
	
	log_debug("Create mosquitto sucessfully!");
	 
	rv = mosquitto_username_pw_set(mosq,mqtt.username,mqtt.passwd);
	if(rv != MOSQ_ERR_SUCCESS)
	{
		log_error("set username and password failure:%s",strerror(errno));
		mosquitto_destroy(mosq);
		mosquitto_lib_cleanup();
		return 0;
	}

	if( (rv = mosquitto_connect(mosq, mqtt.hostname, mqtt.port, 60)) != MOSQ_ERR_SUCCESS )
	{
		log_error("Mosq_Connect() failed: %s", strerror(errno) );
		mosquitto_destroy(mosq) ;
		mosquitto_lib_cleanup() ;
		return 0;
	}
	
	log_debug("Connect %s:%d Sucessfully!", mqtt.hostname, mqtt.port);

    int loop = mosquitto_loop_start(mosq);
    if(loop != MOSQ_ERR_SUCCESS)
    {
        log_error("mosquitto loop error!");
        mosquitto_destroy(mosq) ;
        mosquitto_lib_cleanup() ;
        return 0;
    }

	cur_time = 0;

    while(1)
	{	    
		get_data_flag = 0;

		time(&now_time);
		if( (now_time - cur_time) > interval)
		{
        	if(( pack_data(&mqtt,msg,sizeof(msg),option)) < 0 )
			{
				log_error("get data failure!");
			}

			cur_time = now_time;

			get_data_flag = 1;
		}

		log_debug("%s",msg);

		if(get_data_flag)
		{
			if( mosquitto_publish(mosq,NULL,mqtt.topic,strlen(msg)+1,msg,mqtt.Qos,0) != MOSQ_ERR_SUCCESS )
			{
				log_error("Mosq_Publish() error: %s", strerror(errno));
				mosquitto_destroy(mosq) ;
				mosquitto_lib_cleanup() ;
				return 0;
			}
			else
				log_debug("Publish information of temperature Ok!");
		}
		sleep(2);
	}					
    return 0;
}

